#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "mytbf.h"


typedef struct mytbf_st
{
    int cps;
    int burst;
    int token;
}mytbf_st,*mytbf_pst;

static mytbf_st * mytbf_buf[MYTBF_MAX]={NULL};

static int curr_mytbf_count=0;

void alrm_handler(int s)
{
//	alarm(1);
//	token+=cps;
//	if(token>burst)
//		token=burst;
}

mytbf_t * mytbf_init(int cps,int burst)
{
	if(curr_mytbf_count>MYTBF_MAX)
	{
		perror("curr_mytbf_count is ");
		exit(-1);
	}
	mytbf_pst mytbf_p=malloc(sizeof(mytbf_st));
	if(NULL==mytbf_p)
	{
		perror("mytbf_init():malloc()");
		exit(-1);
	}
	mytbf_p->cps=cps;
	mytbf_p->burst=burst;
	mytbf_p->token=0;
	int i=0;
	for(i=0;i<MYTBF_MAX;i++)
	{
		if(NULL==mytbf_buf[i])
		{
			mytbf_buf[i]=mytbf_p;
			curr_mytbf_count+=1;
			break;
		}
	}
	return mytbf_p;
}

int mytbf_fetchtoken(mytbf_t * pst,int size)
{
	if(NULL==pst)
	{
		perror("mytbf_fetchtoken:pst is null");
		exit(-1);
	}

	mytbf_pst mytbf_p=(mytbf_pst)pst;
	while(0==mytbf_p->token)
	{
		pause();
	}
	int token=mytbf_p->token;
	if(size>=token)
		mytbf_p->token=0;
	else
	{
		mytbf_p->token-=size;
		token=size;
	}
	return token;
}

int mytbf_returntoken(mytbf_t * pst,int size)
{
	if(NULL==pst)
	{
		perror("mytbf_returntoken():pst is NULL");
		return -1;
	}
	if(!size)
		return size;
	mytbf_pst mytbf_p=(mytbf_pst)pst;
	mytbf_p->token+=size;
	return size;
}

int mytbf_destroy(mytbf_t * pst)
{
	if(pst!=NULL)
	{
		free(pst);
		curr_mytbf_count--;
	}
}


